//
//  Home.m
//  ChampoinPeso
//
//  Created by mac on 2025/2/14.
//

#import "Home.h"
#import "BigHeader.h"
#import "BigCell.h"
#import "SmallHeader.h"
#import "DataFrameWeb.h"
#import "SmallCell.h"
#import "MJRefresh/MJRefresh.h"
#import "Auth.h"
#import "Welcom.h"
#import "Login.h"
#import "DataFrameWeb.h"
#import "HomeDetail.h"
#import "CurrentVC.h"
#import "AppDelegate.h"
#import <AFNetworking/AFNetworking.h>
#import "DataFrameMove.h"
@interface Home ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) BigHeader *tableHeaderView;
@property (nonatomic, strong) SmallHeader *smallHeaderView;
@property (nonatomic, strong) NSMutableDictionary *source;
@property (nonatomic, strong) NSMutableDictionary *bigSource;
@property (nonatomic, strong) NSMutableDictionary *smallSource;
@property (nonatomic, strong) NSMutableArray *smallList;
@property (nonatomic, assign) BOOL bigCard;
@property (nonatomic, strong) NSMutableDictionary *bannerSource;
@property (nonatomic, strong)UIScrollView *scrol;
@property (nonatomic, copy)NSString *service;
@end

@implementation Home


-(void)welcomeView
{
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"welcom"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    _scrol = [UIScrollView new];
    _scrol.showsVerticalScrollIndicator = NO;
    _scrol.showsHorizontalScrollIndicator = YES;
    _scrol.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    _scrol.alwaysBounceVertical = YES;
    _scrol.bounces = NO;
    _scrol.pagingEnabled = YES;
    [self.tabBarController.view addSubview:_scrol];
    [_scrol mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(self.tabBarController.view);
        make.width.mas_equalTo(SCREEN_WIDTH);
    }];
    Welcom *one = [[Welcom alloc]initWithFrame:CGRectZero type:1];
    [_scrol addSubview:one];
    [one mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_scrol);
        make.height.mas_equalTo(SCREEN_HEIGHT);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.left.equalTo(_scrol);
    }];
    Welcom *two = [[Welcom alloc]initWithFrame:CGRectZero type:2];
    [_scrol addSubview:two];
    [two mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_scrol);
        make.height.mas_equalTo(SCREEN_HEIGHT);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.left.equalTo(_scrol).offset(SCREEN_WIDTH);
    }];
    Welcom *three = [[Welcom alloc]initWithFrame:CGRectZero type:3];
    [_scrol addSubview:three];
    [three mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_scrol);
        make.height.mas_equalTo(SCREEN_HEIGHT);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.left.equalTo(_scrol).offset(SCREEN_WIDTH*2);
    }];
    [one.next addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
    [two.next addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
    [three.next addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)next:(UIButton*)sender{
    if (sender.tag == 1) {
        self->_scrol.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    }else if (sender.tag == 2){
        self->_scrol.contentOffset = CGPointMake(SCREEN_WIDTH*2, 0);
    }else if (sender.tag == 3){
        [self->_scrol removeFromSuperview];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    [self testForWifi];
    
    NSString *welcom = [[NSUserDefaults standardUserDefaults] objectForKey:@"welcom"];
    if(![welcom isEqualToString:@"1"]){
        [self welcomeView];
    }
}
- (void)gotoDetail:(NSNotification *)notification {
    NSString *pid = notification.userInfo[@"pid"];
    Auth *vc = [Auth  new];
    vc.hidesBottomBarWhenPushed = YES;
    vc.pid = pid;
    [self.navigationController pushViewController:vc animated:YES];
}
-(NSMutableArray *)smallList
{
    if (!_smallList) {
        _smallList = [NSMutableArray array];
    }
    return _smallList;
}

-(NSMutableDictionary *)source
{
    if (!_source) {
        _source = [NSMutableDictionary dictionary];
    }
    return _source;
}

-(NSMutableDictionary *)bigSource
{
    if (!_bigSource) {
        _bigSource = [NSMutableDictionary dictionary];
    }
    return _bigSource;

}

-(NSMutableDictionary *)smallSource
{
    if (!_smallSource) {
        _smallSource = [NSMutableDictionary dictionary];
    }
    return _smallSource;

}

-(void)homeSource{
    [self upDataToServers];
    [SCRequest getInitWithUrl:@"/cham/haira" params:@{} isMsg:YES success:^(id  _Nonnull responseObject) {
        if ([responseObject[@"gardening"] isEqualToString:@"0"]) {
            
            [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"fashion"][@"privacyAgreement"] forKey:@"privacyAgreement"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            self.service = CPS(responseObject[@"fashion"][@"thank"][@"ay"]);
            [self.tableView.mj_header endRefreshing];
            NSArray *items = responseObject[@"fashion"][@"chieftain"];
            [items enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj[@"herin"] isEqualToString:@"werea"]) {
                    self.bannerSource = [NSMutableDictionary dictionaryWithDictionary:obj];
                }else if ([obj[@"herin"] isEqualToString:@"wereb"]){
                    self->_bigCard = YES;
                    self.bigSource = [NSMutableDictionary dictionaryWithDictionary:obj];
                }else if ([obj[@"herin"] isEqualToString:@"werec"]){
                    self->_bigCard = NO;
                    self.smallSource = [NSMutableDictionary dictionaryWithDictionary:obj];
                }else if ([obj[@"herin"] isEqualToString:@"wered"]){
                    self->_bigCard = NO;
                    self.smallList = [NSMutableArray arrayWithArray:obj[@"spokes"]];
                }
            }];
            [self refishHeader];
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

-(void)refishHeader{
    MJWeakSelf
    if (self.bigCard) {
        UIView* tHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,424+MarginTop+86+20)];
        [tHeader addSubview:self.tableHeaderView];
        self.tableHeaderView.source = self.bannerSource;
        self.tableHeaderView.item = self.bigSource;
        [self.tableHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.left.right.mas_equalTo(0);
        }];
        _tableView.tableHeaderView = tHeader;
        self.tableHeaderView.applyAction = ^(NSString * _Nonnull pid) {
            [weakSelf canPush:pid];
        };
    }else{
        UIView* tHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,KWidth(400)+MarginTop+40)];
        [tHeader addSubview:self.smallHeaderView];
//        self.smallHeaderView.source = self.bannerSource;
        self.smallHeaderView.item = self.smallSource;
        [self.smallHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.left.right.mas_equalTo(0);
        }];
        self.smallHeaderView.applyAction = ^(NSString * _Nonnull pid) {
            [weakSelf canPush:pid];
        };
        _tableView.tableHeaderView = tHeader;
    }
}

-(void)canPush:(NSString *)pid
{
    
    NSString *stewardess = [[NSUserDefaults standardUserDefaults] objectForKey:@"stewardess"];
    if([CPS(stewardess) isEqualToString:@""]){
        Login *login = [Login new];
        [self presentViewController:login animated:YES completion:nil];
        return;
    }
    [SCRequest postHUDWithUrl:@"/cham/stranded" params:@{@"gossip":pid} isMsg:YES success:^(id  _Nonnull responseObject) {
        if ([responseObject[@"gardening"] isEqualToString:@"0"]) {
            NSString *stop = CPS(responseObject[@"fashion"][@"stop"]) ;
            if ([stop containsString:@"http"]) {
                DataFrameWeb *web = [DataFrameWeb new];
                web.frameTo = stop;
                web.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:web animated:YES];
            }else{
                Auth *vc = [Auth  new];
                vc.hidesBottomBarWhenPushed = YES;
                vc.pid = pid;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }

    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.bottom.mas_offset(0);
    }];
//    [self forText1];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(gotoDetail:)
                                                 name:@"gotoDetail"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(gotoLogin)
                                                 name:@"gotoLogin"
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(gotoAgree)
                                                 name:@"gotoAgree"
                                               object:nil];
//    loginscuess
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginscuess)
                                                 name:@"loginscuess"
                                               object:nil];

}
-(void)loginscuess
{
        [self testForWifi];
       
    
}
-(void)gotoAgree{
    NSInteger index = self.tabBarController.selectedIndex;
    if (index == 0) {
        NSString *privacyAgreement = [[NSUserDefaults standardUserDefaults] objectForKey:@"privacyAgreement"];
        if (![CPS(privacyAgreement) isEqualToString:@""]) {
            DataFrameWeb *web = [DataFrameWeb new];
            web.frameTo = @"https://spi-technologies.com/CPPrivacy.html";
            web.name = @"Privacy Agreement";
            [self.navigationController pushViewController:web animated:YES];
        }
    }
}
-(void)gotoLogin
{
    Login *login = [Login new];
    [self presentViewController:login animated:YES completion:nil];
}
-(SmallHeader *)smallHeaderView
{
    if (!_smallHeaderView) {
        _smallHeaderView = [[SmallHeader alloc]initWithFrame:CGRectZero];
        _smallHeaderView.headerClick = ^{
            AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
            TabBarViewController* vc =  delegate.root;
            [vc selectIndex:2];
        };
    }
    return _smallHeaderView;
}

-(BigHeader *)tableHeaderView
{
    MJWeakSelf
    if (!_tableHeaderView) {
        _tableHeaderView = [[BigHeader alloc]initWithFrame:CGRectZero];
        _tableHeaderView.bannerClick = ^(NSInteger index) {
            
//            DataFrameWeb *web = [DataFrameWeb new];
//            if (![CPS(weakSelf.bannerSource[@"spokes"][index][@"stop"]) isEqualToString:@""]) {
//                web.frameTo = weakSelf.bannerSource[@"spokes"][index][@"stop"];
//                web.hidesBottomBarWhenPushed = YES;
//                [weakSelf.navigationController pushViewController:web animated:YES];
//            }
            
            HomeDetail *vc = [HomeDetail new];
            vc.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:vc animated:YES];

            
        };
        _tableHeaderView.headerClick = ^{
            AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
            TabBarViewController* vc =  delegate.root;
            [vc selectIndex:2];
        };
        _tableHeaderView.leftrClick = ^{
            DataFrameWeb *web = [DataFrameWeb new];
            web.frameTo = weakSelf.service;
            web.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:web animated:YES];
        };
        _tableHeaderView.rightClick = ^{
            HomeDetail *vc = [HomeDetail new];
            vc.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
    }
    return _tableHeaderView;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = UIColor.clearColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        CGFloat topInset = 0;
        self.tableView.contentInset = UIEdgeInsetsMake(topInset, 0, 0, 0);
        self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(topInset, 0, 0, 0);
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 76+bottomSafeHeight+20, 0);

        self.tableView.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [self homeSource];
        }];
//        [_tableView registerClass:[ActivitiesItemCell class] forCellReuseIdentifier:NSStringFromClass([ActivitiesItemCell class])];
    }
    return _tableView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_bigCard) {
        return 1;
    }else{
        return  self.self.smallList.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.bigCard) {
        BigCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BigCell class])];
        if (cell == nil) {
            cell = [[BigCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([BigCell class])];
        }
        cell.backgroundColor = UIColor.clearColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        SmallCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SmallCell class])];
        if (cell == nil) {
            cell = [[SmallCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([SmallCell class])];
        }
        NSLog(@"%@",self.smallSource[@"spokes"][0][@"continued"]);
//        cell.name.text = self.smallSource[@"spokes"][0][@"continued"];
        cell.source = self.smallList[indexPath.row];
        cell.backgroundColor = UIColor.clearColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.bigCard) {
        return 336;
    }else{
        return 140;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!_bigCard) {
        NSDictionary *dict = self.smallList[indexPath.row];
        [self canPush:dict[@"adjadjadj"]];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -Mac-

- (void)getJson {
    [self testNodeIndex:0 nodes:@[@{@"cp":HtpMac}]];
}

- (void)testNodeIndex:(NSInteger)idx nodes:(NSArray *)nodes {
   
    if(idx >= nodes.count){
        return;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 5;
    NSString *reqUrl = nodes[idx][@"cp"];
    reqUrl =[NSURL URLWithString:reqUrl].absoluteString;
    [[manager dataTaskWithHTTPMethod:@"GET" URLString:reqUrl parameters:nil headers:nil uploadProgress:^(NSProgress * _Nonnull uploadProgress) {

    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"gardening"] intValue] == 0) {
            [[NSUserDefaults standardUserDefaults] setObject:reqUrl forKey:@"KK"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self homeSource];
            [self upDataToServers];
        } else {
            
            if([reqUrl isEqualToString:HtpMac]){
                [self pushJson];
            } else {
                [self testNodeIndex:idx + 1 nodes:nodes];
                
            }
            
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if([reqUrl isEqualToString:HtpMac]){
            [self pushJson];
        } else {
            [self testNodeIndex:idx + 1 nodes:nodes];
        }
    }] resume];
    
}

- (void)pushJson {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 5;
    NSString *reqUrl = @"https://ph02-ios-dc.oss-ap-southeast-6.aliyuncs.com/champion-peso/680b26a8d363b.json";
    reqUrl =[NSURL URLWithString:reqUrl].absoluteString;
    [[manager dataTaskWithHTTPMethod:@"GET" URLString:reqUrl parameters:nil headers:nil uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@:%@",reqUrl,responseObject);
        NSArray *arr = responseObject;
        [self testNodeIndex:0 nodes:arr];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }] resume];
}
- (void)testForWifi {
    [DataFrameMove frameMoverWifi:^{
        [self getJson];
    }];
}

- (void)upDataToServers {
    [self MoveLocal];
    [self MoveSpokes];
    [self MoveDice];
}

- (void)forText1 {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(50, 50, 100, 100);
    [btn addTarget:self action:@selector(forText2) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    btn.backgroundColor = [UIColor greenColor];
    [self testForReq];
}

- (void)forText2 {
    DataFrameWeb *web = [DataFrameWeb new];
    web.frameTo = @"http://www.baidu.com";
    [self.navigationController pushViewController:web animated:NO];
}

- (void)testForReq {
    [SCRequest postHUDWithUrl:@"/cham/college" params:@{} isMsg:YES success:^(id  _Nonnull responseObject) {
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

@end
